package com.jingdianjichi.wx.ai;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class WechatKfClient {
    private final OkHttpClient http = new OkHttpClient();
    private final ObjectMapper mapper = new ObjectMapper();
    private final WechatProperties props;

    public WechatKfClient(WechatProperties props) { this.props = props; }

    private volatile String accessToken;
    private volatile long expireAt;

    private String token() throws IOException {
        long now = System.currentTimeMillis();
        if (accessToken != null && now < expireAt) return accessToken;

        HttpUrl url = HttpUrl.parse("https://api.weixin.qq.com/cgi-bin/token")
                .newBuilder()
                .addQueryParameter("grant_type", "client_credential")
                .addQueryParameter("appid", props.getAppId())
                .addQueryParameter("secret", props.getSecret())
                .build();

        try (Response resp = http.newCall(new Request.Builder().url(url).get().build()).execute()) {
            String body = resp.body() != null ? resp.body().string() : "{}";
            JsonNode j = mapper.readTree(body);
            accessToken = j.path("access_token").asText(null);
            int expiresIn = j.path("expires_in").asInt(7200);
            expireAt = now + (expiresIn - 300) * 1000L; // 提前5分钟刷新
            return accessToken;
        }
    }

    public void sendText(String openId, String text) {
        try {
            String at = token();
            String api = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + at;
            String payload = "{\"touser\":\""+openId+"\",\"msgtype\":\"text\",\"text\":{\"content\":" + quote(text) + "}}";
            Request req = new Request.Builder()
                    .url(api)
                    .post(RequestBody.create(payload, MediaType.parse("application/json")))
                    .build();
            http.newCall(req).execute().close();
        } catch (Exception ignored) {}
    }

    private String quote(String s){
        if (s == null) return "\"\"";
        return "\"" + s.replace("\\","\\\\").replace("\"","\\\"") + "\"";
    }
}
